<template>
	<view class="base-resource-detail">
		<!-- <uni-icons v-if="!tabVisible" class="left-icon" type="left" size="24" @click="goBack"></uni-icons> -->
		
		<view v-if="!tabVisible" class="left-icon">
			<navSearchBar  :zIndex="titleZindex" background="" :initEenter="initEenter"></navSearchBar>
		</view>
		<view v-if="tabVisible" class="top-operate">
			<navSearchBar  :title="baseName"  :zIndex="titleZindex" :initEenter="initEenter"></navSearchBar>
			<view class="top-operate-tab" :style="{zIndex:titleZindex}">
				<tn-tabs  :list="tabList" :isScroll="false" height="88" :current="current" name="tab-name" :bold="true" activeColor="#000000" inactiveColor="#5B5D65" @change="changeTab" :barWidth="60" :barHeight="4"></tn-tabs>
			</view>
		</view>
		
		<scroll-view  class="custom-tabbar-page" scroll-y enable-back-to-top >
			
				
				
				<image class="title-picture" :src="bgImage" mode="widthFix"></image>
				<view class="body-field">
					<view  class="title-card" >
						<view class="name-field">
							<text class="title">{{baseName}}</text>
							<view class="right-type">
								<image src="/static/icon/union.png" mode=""></image>
								<text >{{typeName}}</text>
							</view>
						</view>
						<view  class="cooperation-field">
							<text class="cooperation-label">{{cooperationLevel}}</text>
							<tn-rate class="rank" gutter="20" size="40" v-model="starLevel" :count="5"  activeColor="#FFB547" inactiveColor="#DADADA" activeIcon="star-fill" inactiveIcon="star-fill" :disabled="true"></tn-rate>
						</view>
						<view class="location-field" @click="locationTo">
							<view class="icon-field">
								<text class="tn-icon-location"></text>
							</view>
							<view class="location-label">
								<text class="simple-address text-label">{{simpleAddress}}</text>
								<text class="detail-address text-label">{{detailAddress}}</text>
							</view>
						
						</view>
					</view>
					<view  class="introduce-card" >
						<text class="title">基地介绍</text>
						<view>
							<my-rich-text :htmlContent="content"></my-rich-text>
							<!-- <view v-html="content"></view> -->
						</view>
					</view>
					<view class="nearby-card">
						<view class="title">
							<uni-icons type="map"></uni-icons>
							<text style="margin-left: 20rpx;">附近基地</text>
						</view>
						<view class="list">
							<view v-for="(item, index) in nearbyList" :key="index" class="list-item" @click="routeToBase(item)">
								<image :src="item.picture"></image>
								<view class="text-field">
									<view class="text-label">
										<text class="title text-label-all">{{item.title}}</text>
										<text class="address text-label-all">{{item.address}}</text>
										<text class="distance">直线距离<text class="address" style="margin:0 10rpx">{{item.distance}}</text>
										
										</text>
										
									</view>
									<text class="tn-icon-right"></text>
								</view>
							</view>
						</view>
					</view>
				</view>
			
		</scroll-view>
		<wx-share ref="share"></wx-share>
		<view  v-if="visibleByAdmin">
			<my-guide-nav :navOptions="navOptions" :buttonOptions="customButtonGroups"  @buttonClick="onButtonClick" @textClick="onOptionClick"></my-guide-nav>
		</view>
		<view v-else>
			<userGuideNav  :userInfo="contactInfo"></userGuideNav>
		</view>
	</view>
</template>

<script>
	import {USER_INFO,ROLE_TYPE} from '@/common/util/constants.js';
	import userGuideNav from '@/pages/common/user-guide-nav.vue';
	import {throttle} from "@/common/util/util";
	import pageShowOrHideMixin from '@/common/mixin/pageShowOrHideMixin';
	export default {
		mixins:[pageShowOrHideMixin],
		components:{
			userGuideNav
		},
		data() {
			return {
				initEenter:false,
				roleType:ROLE_TYPE.COMMON,
				contactInfo:{},
				titleZindex:100,
				tabList: [
					{
					  'tab-name': '基本信息'
					}
					,{
					 'tab-name': '基地简介',
					}
					, {
					 'tab-name': '附近基地',
					 
					}
				],
				current: 0,
				bgImage:'',
				tabVisible:false,
				baseName:'',
				typeName:'',
				cooperationLevel:'',
				starLevel:3,
				simpleAddress:'',
				detailAddress:'skj案说法就是雷锋精神独立房间急急急急急急',
				content:'',
				navOptions:[ {
					icon: 'star',
					text: '收藏',
					iconColor:'#656371',
					fontColor:'#656371',
					imgUrl:'/static/icon/collect.png'
				  },{
					icon: 'write',
					text: '标注',
					iconColor:'#656371',
					fontColor:'#656371',
					imgUrl:'/static/icon/label.png',
				  }],
				customButtonGroups:[{
					text: '分享基地',
					backgroundColor: '#05C160',
					icon:'tn-icon-send',
					color: '#FFFFFF',
					imgUrl:'/static/icon/share.png'
				  }],
				  nearbyList:[
					  // {title:'111111111111111',
					  // address:'2222222222222'},
					  // {title:'111111111111111',
					  // address:'2222222222222'},
					  // {title:'111111111111111',
					  // address:'2222222222222'},
					  // {title:'111111111111111',
					  // address:'2222222222222'},
					  // {title:'111111111111111',
					  // address:'2222222222222'},
					  // {title:'111111111111111',
					  // address:'2222222222222'},
					  ],
					  currentPath:''
				
			}
		},
		computed:{
			visibleByAdmin(){
				return this.roleType == ROLE_TYPE.ADMIN;
			}
		},
		onShareAppMessage(object){
			console.log('onShareAppMessage',object)
			return {
			      title: this.baseName+'—基地资源',
			      path: this.currentPath,
			      
			    }
		},
		onLoad(e){
			console.log('onLoad',e,this.$Route.query)
			this.baseId = this.$Route.query.id;
			let role_id;
			let userInfo = uni.getStorageSync(USER_INFO);
			let shareId;
			if(userInfo) {
				role_id = userInfo.role_id;
				this.userId = userInfo.id;
			}
			if(e&&e.id){
				this.baseId = e.id;
			}
			if(e&&e.scene){//扫码，如果扫码人已经打开过该app会走这
				let scene = decodeURIComponent(e.scene)
				let relist = scene.match(/id=(.*)/)
				console.log('options',relist)
				let sceneId;
				if(relist[1]){
					sceneId = relist[1];
				}
				this.baseId = sceneId;
			}
			if(e && e.user_id){//用户先点开一个人的分享已经启动该app，在点开另一个的分享，就会走这不会走下面启动参数还是之前的
				shareId = e.user_id;
			}
			let launchOptions = uni.getLaunchOptionsSync();
			console.log('scence',launchOptions,launchOptions.query.scene)
			console.log('scence',decodeURIComponent(launchOptions.query.scene))
			let pages = getCurrentPages();
			if(!this.baseId && launchOptions.path == "pages/resource/base/detail"){
				
				
				if(launchOptions.query.id || launchOptions.query.scene){
					////从分享得地方启动得 或扫码
					let sceneId;
					if(launchOptions.query.scene) {
						let scene = decodeURIComponent(launchOptions.query.scene)
						let relist = scene.match(/id=(.*)/)
						console.log(relist)
						if(relist[1]){
							sceneId = relist[1];
						}
					}
					if(pages.length == 1){
						this.baseId = launchOptions.query.id || sceneId;
						this.initEenter = true;
						shareId = launchOptions.query.user_id;
					}
				} else {
					this.$tip.alert('传参无效')
				}
			}
			
			console.log('role_id',role_id,this.roleType)
			if(role_id == 1) {
				this.roleType = ROLE_TYPE.ADMIN;
			} else {
				this.roleType = ROLE_TYPE.COMMON;
				if(shareId){//c端用户点击分享的话
					this.userId = shareId;
				}
			}
			this.currentPath = `/pages/resource/base/detail?id=${this.baseId}&user_id=${this.userId}`;
			
			this.getDetail().then((res) => {
				
				if(this.roleType == ROLE_TYPE.ADMIN){
					this.getCollectStatus();
				}
				this.getNearByList();
				//这时详情接口已返回
				
				this.sendToServerOnShow(this.baseName, this.bgImage);
				
				
			})
		
			let prevPage = pages[pages.length - 2];
			if(prevPage){
				prevPage.$vm.detail_page_flag = true;
			}
			this.allFiledThrottle = throttle(this.allFiledChange,500);
			
		},
		created(){
			console.log('created')
			this.tabIntroduceVisible = false;
			this.tabNearbyVisible = false;
			this.tabTitleVisible = true;
			
		},
		onReady(){
			
			console.log('onReady',this.scrollFlag)
			const { windowHeight } = uni.getSystemInfoSync(); // 获取页面高度
			this.windowHeight = windowHeight;
			this.threshold = this.windowHeight / 2 - 20;
			
		},
		mounted(){
			console.log('mounted',this)
			
			
			
		},
		onUnload(){
			
			console.log('onUnload')
		},
		beforeDestroy(){
			console.log('beforeDestroy')
		},
		destroyed(){
			console.log('destroyed')
		},
		onPageScroll(e){
			this.allFiledThrottle(e);
			// console.log('eeeeeeeee',e)
		},
		methods: {
			initInterSection(){
				let halfHeight = this.windowHeight / 2 - 20;
				this.observerTitle = uni.createIntersectionObserver(this,{thresholds:[0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.98,0.99,1]});
				this.observerTitle.relativeToViewport({top:-halfHeight}).observe('.title-card',(res) => {
					console.log('title-card',res)
					// this.titleDebunce(res);
					this.titleFieldChange(res)
					
				})
				this.observerIntroduce = uni.createIntersectionObserver(this,{thresholds: [0,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1]});
				this.observerIntroduce.relativeToViewport({top:-halfHeight}).observe('.introduce-card',(res) => {
					console.log('introduce-card',res)
					// this.allFiledDebounce(res,1);
					// this.introduceDebounce(res)
					this.introduceFieldChange(res)
					
				})
				this.observerNearby = uni.createIntersectionObserver(this,{thresholds:[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]});
				this.observerNearby.relativeToViewport({top:-halfHeight}).observe('.nearby-card', (res) => {
					// console.log('nearby-card',res)
				    this.nearByFieldChange(res)
				 
				})
			},
			allFiledChange({scrollTop}){
				this.titleFieldChange(scrollTop);
				this.introduceFieldChange(scrollTop);
				this.nearByFieldChange(scrollTop)
				// console.log('222',scrollTop)
				
			},
			nearByFieldChange(scrollTop){
				uni.createSelectorQuery().select('.nearby-card').boundingClientRect((res)=>{
					console.log('tittitititi',res,this.scrollFlag)
					let selfTop = res.top;
					let selfBottom = res.bottom;
					let thresholdTop = this.threshold;
					if(selfTop < thresholdTop && selfBottom +10 > thresholdTop){
						if(this.scrollFlag){
							return;
						}
						// if(this.feature){
						this.current = 2;
						this.tabNearbyVisible = true;
						
					} else {
						this.tabNearbyVisible = false;
					}
					this.tabVisible = this.current == 1 || this.current == 2;
					// this.tabVisible = this.tabIntroduceVisible || this.tabNearbyVisible;
					console.log('2',this.tabIntroduceVisible,this.tabNearbyVisible,this.tabVisible,this.current)
				}).exec()
				
			},		
			introduceFieldChange(scrollTop){
				uni.createSelectorQuery().select('.introduce-card').boundingClientRect((res)=>{
					console.log('tittitititi',res,this.scrollFlag)
					let selfTop = res.top;
					let selfBottom = res.bottom;
					let thresholdTop = this.threshold;
					if(selfTop < thresholdTop && selfBottom +10 > thresholdTop){
						if(this.scrollFlag){
							return;
						}
						// if(this.feature){
						this.current = 1;
						this.tabIntroduceVisible = true;
						
					} else {
						this.tabIntroduceVisible = false;
					}
					this.tabVisible = this.current == 1 || this.current == 2;
					// this.tabVisible = this.tabIntroduceVisible || this.tabNearbyVisible;
					console.log('1',this.tabIntroduceVisible,this.tabNearbyVisible,this.tabVisible,this.current)
				}).exec()
			},
			titleFieldChange(scrollTop){
				
				uni.createSelectorQuery().select('.title-card').boundingClientRect((res)=>{
					console.log('tittitititi',res,this.scrollFlag)
					let selfTop = res.top;
					let selfBottom = res.bottom;
					let thresholdTop = this.threshold;
					if(selfTop < thresholdTop && selfBottom +10 > thresholdTop){
						if(this.scrollFlag){
							return;
						}
						// if(this.feature){
						this.current = 0;
						this.tabTitleVisible = true;
						
					} else {
						this.tabTitleVisible = false;
					}
					this.tabVisible = this.current == 1 || this.current == 2;
					// this.tabVisible = this.tabIntroduceVisible || this.tabNearbyVisible;
					console.log('0',this.tabIntroduceVisible,this.tabNearbyVisible,this.tabVisible,this.current)
				}).exec()
			},
			getNearByList(){
				const data = {
					id:this.baseId,
					latitude:this.latitude,
					longitude:this.longitude
					// distance:20,
				}
				this.$http.get('/api/business/place/nearby',data).then((res) => {
					if(res.data.status == 200) {
						console.log('jidi',res.data);
						this.nearbyList = res.data.data||[];
					}
				})
			},
			getDetail(){
				
				return new Promise((resolve,reject) =>{
					this.$http.get(`/api/business/place/view/${this.baseId}`,{is_user:1, user_id:this.userId}).then((res) => {
						let result = res.data;
						if(result.status == 200) {
							this.palceId = result.data.id;
							console.log('jidi',res.data);
							this.bgImage =result.data.picture;
							this.baseName = result.data.title;
							this.typeName = result.data.category.title;
							this.cooperationLevel = result.data.cooperation_level.text;
							this.starLevel = result.data.star_level.value;
							this.simpleAddress = result.data.province_id.text + '/'+ result.data.city_id.text + '/' + result.data.region_id.text;
							this.detailAddress = result.data.province_id.text + result.data.city_id.text + result.data.region_id.text + result.data.address;
							this.content = result.data.detail&&result.data.detail.content||'';
							this.longitude = result.data.longitude;
							this.latitude = result.data.latitude;
							
							this.contactInfo.name = result.data.user.nickname;
							this.contactInfo.imgUrl = result.data.user.avatar;
							this.contactInfo.position = result.data.user.detail.position;
							this.contactInfo.phone = result.data.user.username;
							resolve()
						}
					})
				})
				
			},
			getCollectStatus(){
				let data = {
					place_id:this.palceId,
					
				}
				this.$http.get('/api/member/business/collect/place/status',data).then((res) => {
					if(res.data.status == 200){
						this.collectStatus = res.data.data;
						if(this.collectStatus){
							this.navOptions[0].imgUrl = '/static/icon/collect-fill.png';
							this.navOptions[0].icon = 'star-fill';
							this.navOptions[0].text = '已收藏'
						} else {
							this.navOptions[0].imgUrl = '/static/icon/collect.png';
							this.navOptions[0].icon = 'star';
							this.navOptions[0].text = '收藏'
						}
						
					}
					
				})
			},
			onOptionClick(index) {
				console.log('onOptionClick',index)
				if(index == 0) {
					//收藏
					this.collect();
				} else if(index == 1) {
					//标注
					this.$Router.push({name:'baseLabel',query:{img:this.bgImage,title:this.baseName,place_id:this.palceId}});
				}
			},
			onButtonClick(e){
				console.log('onButtonClick',e)
				this.$refs.share.open(this.bgImage);
				const data = {
					place_id:this.palceId,
					path: this.currentPath
				}
				this.$http.post('/api/member/business/share/place/handle',data).then((res) => {
					
				})
			},
			collect(){
				let data = {
					place_id:this.palceId,
					
				}
				
				this.$http.post('/api/member/business/collect/place/handle',data).then((res) => {
					
					if(res.data.status == 200) {
						
						if(!this.collectStatus){
							this.collectStatus = true;
							this.$tip.success('收藏成功')
							this.navOptions[0].icon = 'star-fill';
							this.navOptions[0].imgUrl = '/static/icon/collect-fill.png';
							this.navOptions[0].text = '已收藏'
						} else {
							this.collectStatus = false;
							this.$tip.success('取消收藏')
							this.navOptions[0].icon = 'star';
							this.navOptions[0].imgUrl = '/static/icon/collect.png';
							this.navOptions[0].text = '收藏'
						}
					} else {
						
					}
				})
				
			},
			goBack(){
				uni.navigateBack(-1)
			},
			locationTo() {
				
				// this.$Router.push({name:'map',query:{
				// 	longitude:this.longitude,
				// 	latitude: this.latitude,
				// 	placeName:this.baseName,
				// 	detailAddress:this.detailAddress}})
				uni.openLocation({
				  longitude: parseFloat(this.longitude),
				  latitude: parseFloat(this.latitude),          
				  name: this.placeName,
					address: this.detailAddress,
					success: function (res) {
					console.log('打开系统位置地图成功')
				},
				fail: function (error) {
				  console.log(error)
				},
				})
			},
			routeToBase(item){
				this.$Router.push({name:'baseResourceDetail',query:{id:item.id}})
			},
			changeTab(index){
				
				let offetHeight = this.windowHeight/2;
				// if(index > this.current){
				// 	//向下
				// 	offetHeight = 50;
				// } else {
				// 	offetHeight = -50;
				// }
				this.current = index;
				let className = '';
				if(index == 0){
					className = '.title-card';
				}else if(index == 1) {
					className = '.introduce-card';
				} else {
					className = '.nearby-card';
				}
				uni.createSelectorQuery()
				.select(className)
				.boundingClientRect((con) => {
				  console.log(con,className);
				  // 获取点击要跳转的锚点信息
				  uni
					.createSelectorQuery()
					.select(".base-resource-detail")
					.boundingClientRect((res) => {
					  // console.log(res);
					  console.log(con.top - res.top,res);
					  let scrollTop = 0;
					 
					 scrollTop = con.top - res.top - this.windowHeight + offetHeight + 40;
					 // < 0 ?0 : con.top - res.top - windowHeight;
					  // console.log('dcrooltp',con.top - res.top - windowHeight,scrollTop)
					  // 获取根元素要滑动的元素
					  uni.pageScrollTo({
						// selector: className, // 滑动的元素
						// duration: 1500, // 过渡时间
						scrollTop: scrollTop, // 到达距离顶部的top值
					  });
					  this.scrollFlag = true;
					  if(this.current == 0){
						this.tabVisible = false;
					  }
					  setTimeout(()=>{
						  console.log('wwwww',scrollTop)
						  this.scrollFlag = false;
					  },600)
					})
					.exec();
				})
				.exec();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.base-resource-detail{
		background-color: #F1F2F4;
		min-height: 100vh;
		
		.left-icon{
			position: fixed;
			
			z-index:1;
		}
		.top-operate{
			position: fixed;
			
			z-index:1;
			width: 100%;
		}
		.top-operate-tab{
			height: 128rpx;
			width: 100%;
			// display: flex;
			background-color: #fff;
			// border-bottom: 2rpx solid #EFEFEF;
			// display: flex;
			// justify-content: space-around;
			// align-items: center;
			// .active-style{
			// 	color: #EE8731;
			// }
		}
		.title-picture{
			// height: 750rpx;
			width:100%;
		}
		.custom-tabbar-page{
			padding-bottom: calc(112rpx + env(safe-area-inset-bottom));
			// height: calc(100vh - 112rpx - env(safe-area-inset-bottom) / 2);
			.body-field{
				margin-left: 30rpx;
				margin-right: 30rpx;
				position: relative;
				top:-36rpx;
				.title-card{
					width: 690rpx;
					
					background-color: #FFFFFF;
					border-radius: 10rpx;
					
					position: relative;
					margin-bottom:30rpx;
					
					.name-field{
						padding-top:60rpx;
						display: flex;
						justify-content: space-between;
					}
					.title{
						
						flex:1;
						padding-left: 20rpx;
						word-wrap:break-word;
						word-break: break-all;
						font-size: 56rpx;
						line-height: 62rpx;
						color:#616571;
						font-weight: $Semibold;
						
						
					}
					.right-type{
						
						margin-left: 86rpx;
						padding: 0 20rpx;
						
						height: 62rpx;
						background-color: #485160;
						color: #FFFFFF;
						font-size: 28rpx;
						font-weight: $Semibold;
						display: flex;
						justify-content: center;
						align-items: center;
						border-top-left-radius: 10rpx;
						border-bottom-left-radius: 10rpx;
						text{
							margin-left: 18rpx ;
						}
						image{
							width: 36rpx;
							height: 26rpx;
						}
					}
					.cooperation-field{
						clear: both;
						display: flex;
						justify-content: space-between;
						padding: 20rpx 30rpx 20rpx 20rpx;
						.cooperation-label{
							font-size: 32rpx;
							color: #656668;
							
						}
						
					}
					
					.location-field{
						
						
						padding:20rpx 30rpx 30rpx;
						
						border-radius: 10rpx;
						.icon-field{
							float: left;
							background-color: #EAEBEF;
							width: 120rpx;
							height: 140rpx;
							text-align: center;
							line-height: 140rpx;
							border-top-left-radius: 10rpx;
							border-bottom-left-radius: 10rpx;
							text{
								font-size: 52rpx;
								color:#616571;
							}
						}
						.location-label{
							background-color: #F5F6F8;
							overflow: hidden;
							height: 100%;
							padding:30rpx;
							.simple-address{
								font-size: 32rpx;
								margin-bottom: 20rpx;
								color:#656668;
								line-height: 32rpx;
							}
							.detail-address{
								font-size: 28rpx;
								color: #9A9A9A;
								line-height: 28rpx;
							}
							.text-label{
								 overflow: hidden;
								 text-overflow: ellipsis;
								 white-space: nowrap;
								 display: block;
							}
						}
					}
				}
				.introduce-card{
					background-color: #FFFFFF;
					padding:40rpx;
					margin-bottom: 30rpx;
					border-radius: 10rpx;
					.title{
						padding:20rpx 0 40rpx;
						font-size: 40rpx;
						color: #616571;
						font-weight: $Semibold;
					}
				}
				.nearby-card{
					background-color: #FFFFFF;
					padding:60rpx 40rpx 0;
					.title{
						
						line-height: 40rpx;
						color:#616571;
						font-size: 40rpx;
						font-weight: $Semibold;
					}
					.list{
						padding:40rpx 0;
						.list-item:last-child{
							margin-bottom: 0;
						}
						.list-item{
							display: flex;
							margin-bottom: 40rpx;
							image{
								width: 208rpx;
								height: 146rpx;
								border-radius: 10rpx;
							}
							.text-field{
								display: flex;
								align-items: center;
								.text-label{
									display: flex;
									flex-direction: column;
									margin:0 70rpx 0rpx 20rpx;
									width: 276rpx;
									.text-label-all{
										overflow: hidden;
										text-overflow: ellipsis;
										white-space: nowrap;
										margin-bottom: 20rpx;
									}
									.title{
										font-size: 32rpx;
										line-height: 32rpx;
										color: #616571;
										font-weight: $Semibold;
									}
									.address{
										font-size: 28rpx;
										line-height: 28rpx;
										color: #616571;
									}
									.distance{
										color: #999999;
										font-size: 28rpx;
										line-height: 28rpx;
									}
								}
							}
						}
						
					}
				}
			}
		}
	}

</style>
